<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :minHeight="500" :title="getTitle" width="1000px" destroy-on-close>
    <Tabs v-model:activeKey="activeKey" :tabBarGutter="5" :tabBarStyle="state.tabBarStyle" tab-position="left">
      <TabPane tab="通过链接邀请" key="fromLink" forceRender v-if="state.inviteWay === 'fromLink'">
        <InviteUserByLink :invite="state.oldInvite" ref="inviteLinkRef" @change="handleLinkChange" />
      </TabPane>
    </Tabs>

    <template #footer>
      <Button type="primary" v-if="activeKey === 'fromExistUser'" @click="handleSubmit">
        {{ state.inviteWay === "link" ? "添加到至企业" : "确定" }}
      </Button>
      <Button type="primary" v-if="activeKey === 'fromLink' && !state.oldInvite" @click="handleSubmit"> 创建并复制链接 </Button>
      <Button type="primary" v-if="activeKey === 'fromLink' && state.oldInvite" @click="handleSubmit"> 复制链接 </Button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref, toRaw, reactive, computed } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { Tabs, TabPane, Button } from "ant-design-vue"
  import InviteUserByLink from "./InviteUserByLink.vue"
  import * as userApi from '/@/api/iam/user'
  const emit = defineEmits(["select", "register"])
  const checkedKeys = ref<Array<string | number>>([])
  const activeKey = ref("fromLink")
  const inviteLinkRef = ref<any>()
  const state = reactive({
    inviteWay: "fromExistUser",
    // 是否为平台用户, 会查询所有用户
    selectPlatformUser: false,
    // 是否单选表格数据
    singleSelect: false,
    oldInvite: undefined,
    tabBarStyle: {
      width: "130px",
      marginLeft: "-20px",
      minHeight: "500px",
    },
  })

  const handleLinkChange = (userInvite) => (state.oldInvite = userInvite)

  const getTitle = computed(() => "邀请企业成员")

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    try {
      checkedKeys.value = []
      state.inviteWay = data?.inviteWay || state.inviteWay
      state.singleSelect = !!data?.singleSelect
      state.selectPlatformUser = data?.selectPlatformUser || state.selectPlatformUser
      state.oldInvite = await userApi.getUserInvite({})
      activeKey.value = state.inviteWay && state.inviteWay === "fromLink" ? "fromLink" : "fromExistUser"
      setModalProps({ draggable: false })
    } catch(ex) {
      console.error(ex)
    }
  })

  async function handleSubmit() {
    try {
      setModalProps({ loading: true })
      setModalProps({ confirmLoading: true })
       await inviteLinkRef.value.save()
    } finally {
      setModalProps({ loading: false })
    }
  }
</script>
